package com.alex.algorithm.medium;

import com.alex.algorithm.easy.LinkedListNode;

public class swapNodesInPairs {

    public static void main(String[] args) {
        LinkedListNode n1 = new LinkedListNode();
        n1.setVal(1);
        LinkedListNode n2 = new LinkedListNode();
        n1.setNext(n2);
        n2.setVal(2);
        LinkedListNode n22 = new LinkedListNode();
        n22.setVal(3);
        n2.setNext(n22);
        LinkedListNode n3 = new LinkedListNode();
        n3.setVal(4);
        n22.setNext(n3);
        LinkedListNode head = swap(n1);


        while (head.getNext() != null) {
            System.out.println(head);
            head = head.getNext();
        }
    }

    public static LinkedListNode swap(LinkedListNode node) {
        LinkedListNode dummyNode = new LinkedListNode();
        dummyNode.setNext(node);
        LinkedListNode left = dummyNode;

        while (left.getNext() != null && left.getNext().getNext() != null) {
            LinkedListNode first = left.getNext();
            LinkedListNode second = left.getNext().getNext();
            first.setNext(second.getNext()); // set的顺序很重要
            second.setNext(first);
            left.setNext(second);

            left = left.getNext().getNext();
        }
        return dummyNode.getNext();
    }
}
